package blue.datacenter2;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;

import blue.datacenter2.Message;
import blue.datacenter2.MessageLog;

public class MachineHandler extends Thread implements Handler{
	private SocketClient machine_conn_;
	private ArrayList<ZmqPublisher> slave_pub_list_;
	private ZmqPublisher log_pub_;

	public MachineHandler(SocketClient conn, ZmqPublisher log_pub){
		machine_conn_ = conn;
		log_pub_ = log_pub;
		slave_pub_list_ = new ArrayList<ZmqPublisher>();
	}

	public void addPubConn(ZmqPublisher pub){
		slave_pub_list_.add(pub);
	}

	private void pubMsglog(String id, boolean to_machine,Message msg) {
		// Publish Message
		String msg_id = id;
		String msg_send = null;
		String msg_recv = null;
		if (to_machine) {
			msg_send = "TM";
			msg_recv = msg.ip+":"+msg.port;;
		}else {
			msg_send = msg.ip+":"+msg.port;
			msg_recv = "TM";
		}
		String msg_data = msg.data;
		MessageLog log = new MessageLog(msg_id,msg_send,msg_recv,msg_data);
		log_pub_.publish(log.toJSON());
	}
	
	public void run(){
		try {
			while(true){
				// Recv from machine
				String mach_msg = machine_conn_.read();
				System.out.println("Recv from Machine >"+mach_msg);
				if (mach_msg==null) {
					if(!machine_conn_.reconnection()) {
						System.out.println("Error: Reconnect fail.");
						System.exit(-1);
					}
				}
				String ip = machine_conn_.getIP();
				String port = String.valueOf(machine_conn_.getPort());
				// Send Message to slave
				Message msg = new Message(ip,port,mach_msg);
				String json_msg = msg.toJSON();
				System.out.println("Write to slave > "+json_msg);
				for (Iterator<ZmqPublisher> it = slave_pub_list_.iterator();it.hasNext();) {
					it.next().publish(json_msg);
				}
				// Write Message to Logger
				pubMsglog("1", false, msg);
			}
		}catch(IOException e) {
			System.out.println("Fatal Error > Machine connection broken.");
			e.printStackTrace();
		}
	}

}